//
//  ZLComposeViewController.swift
//  ZLWeibo
//
//  Created by zhanglongtao on 17/1/5.
//  Copyright © 2017年 hanju001. All rights reserved.
//

import UIKit
import SVProgressHUD

//撰写微博控制器
class ZLComposeViewController: UIViewController {
    //文本编辑
    @IBOutlet weak var textView: ZLComposetextView!

    //底部工具栏
    @IBOutlet weak var toolBar: UIToolbar!
    //工具栏底部约束
    @IBOutlet weak var toolBarBottomConstant: NSLayoutConstraint!
    //表情输入视图
    lazy var emotionView: ZLEmotionInputView = ZLEmotionInputView.inputView { [weak self] (emotion) in
        
        self?.textView.insertEmotion(em: emotion)
        
    }
    /// 逐行选中文本并且设置属性
    /// 如果想要调整间距，可以增加一个空行，设置空行的字体
    @IBOutlet var titleLabel: UILabel!
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        
        
       setupUI()
        //监听键盘通知
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardChange), name: NSNotification.Name.UIKeyboardWillChangeFrame, object: nil);
    }
    @objc fileprivate func keyboardChange(n: NSNotification) {
        
        guard let rect = (n.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue, let duration = (n.userInfo?[UIKeyboardAnimationDurationUserInfoKey] as? NSNumber)?.doubleValue
            else{
            
            return
        }
        

        let offset = view.bounds.height - rect.origin.y
        //更新底部约束
        toolBarBottomConstant.constant = offset
        UIView.animate(withDuration: duration) { 
            
            self.view.setNeedsDisplay()
        }
        
    }
    @objc fileprivate func closeVC(){
        
        dismiss(animated: true, completion: nil)
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        textView.becomeFirstResponder()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        textView.resignFirstResponder()
    }
    
    lazy var sendButton: UIButton = {
        
        let btn = UIButton()
        btn.setTitle("发布", for: [])
        btn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        btn.setTitleColor(UIColor.white, for: [])
        btn.setTitleColor(UIColor.gray, for: .disabled)
        //设置背景图片
        
        btn.setBackgroundImage(UIImage(named: "common_button_orange"), for: [])
        btn.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), for: .highlighted)
        btn.setBackgroundImage(UIImage(named: "common_button_white_disable"), for: .disabled)
        
        btn.frame = CGRect(x: 0, y: 0, width: 45, height: 30)
        btn.addTarget(self, action: #selector(clickPostStatus), for: .touchUpInside)
        return btn
    }()
    
    @objc private func clickPostStatus() {
        
        print("发布微博")
        
        SVProgressHUD.show()
       let text = textView.emotionText
        
        
        let image: UIImage? = nil //UIImage(named: "df73fb6347597eb25a478336d8e7e27e_b.jpg")
        ZLNetWorkManager.shared.postStatus(status: text,iamge: image) { (result, isSuccess) in
            
            print(result ?? "")
            //SVProgressHUD.dismiss()
            SVProgressHUD.setDefaultStyle(.dark)
            let message = isSuccess ? "发布成功" : "网络不给力"
            
            
            if isSuccess {
                SVProgressHUD.showSuccess(withStatus: message)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                    
                    SVProgressHUD.setDefaultStyle(.light)
                    
                    self.closeVC()
                })
            }else{
                SVProgressHUD.showError(withStatus: message)
                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                    
                    SVProgressHUD.dismiss()
                })
            }
            
        }
        
    }
    //切换表情键盘
    @objc fileprivate func emoticonKeyboard(){
       
        textView.inputView = textView.inputView == nil ? emotionView : nil
        
        textView.reloadInputViews()
    }
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
}
/*
 通知： 一对多 只要注册的监听者，在注销通知之前，都可以接受通知
 代理： 一对一 最后设置的代理对象有效
 
 --代理是发生事件时，直接让代理执行方法
 代理的效率更高
 直接的反向传值
 --通知是事件放生时，将通知发送给通知中心，通知中心在‘广播’通知
 通知相对第一点
 如果嵌套的层次比较深，可以使用通知传值
 */
extension ZLComposeViewController: UITextViewDelegate {
    
    func textViewDidChange(_ textView: UITextView) {
       
        sendButton.isEnabled = textView.hasText
    }
}
private extension ZLComposeViewController {
    
    func setupUI() {
        
        view.backgroundColor = UIColor.white
        
        setupNavigationBar()
        
        setupToolBar()
        
    }
    
    func setupToolBar() {
        
        let itemSettings = [["imageName": "compose_toolbar_picture"],
                            ["imageName": "compose_mentionbutton_background"],
                            ["imageName": "compose_trendbutton_background"],
                            ["imageName": "compose_emoticonbutton_background", "actionName": "emoticonKeyboard"],
                            ["imageName": "compose_add_background"]]
        
        var items = [UIBarButtonItem]()
        for s in itemSettings {
            
            let btn = UIButton()
            guard let imageName = s["imageName"] else {
                
                return
            }
            let image = UIImage(named: imageName)
            let imageHL = UIImage(named: imageName + "_highlighted")
            
            btn.setImage(image, for: [])
            btn.setImage(imageHL, for: .highlighted)
            
            btn.sizeToFit()
            //判断 actionName
            if let actionName = s["actionName"] {
                
                btn.addTarget(self, action: Selector(actionName), for: .touchUpInside)
            }
            //追加按钮
            items.append(UIBarButtonItem(customView: btn))
            //追加弹簧
            items.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
        }
        //删除末尾弹簧
        items.removeLast()
        
        toolBar.items = items
        
        
    }
    
    // 设置导航栏
    func setupNavigationBar() {
        
        
         navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", target: self, action: #selector(closeVC))
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: sendButton)
        
        navigationItem.titleView = titleLabel
        
        sendButton.isEnabled = false
    }
    
}
